import React from 'react';
import { inject, observer } from 'mobx-react';
import { toJS } from 'mobx';
import { Button, Form, Spin, Icon } from 'antd';
import SubscribeDialog from './subscribe/SubsribeDialog';
import { Synergy } from '../components/Portal/Portal';
import {
  WeaTop,
  WeaRightMenu,
  WeaErrorPage,
  WeaTools,
  WeaTab,
  WeaSearchGroup,
  WeaNewScroll,
  WeaDialog,
  WeaTextarea,
  WeaLeftTree,
  WeaLeftRightLayout,
  WeaBrowser,
  WeaFormItem,
  WeaLocaleProvider,
} from 'ecCom';
import { WeaTableNew, WeaSwitch } from 'comsMobx';
import { GetUrlParam } from '../util/index';

const { WeaTable } = WeaTableNew;
const getLabel = WeaLocaleProvider.getLabel;
@inject('docSubscribeStore')
@observer
class Subscribe extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      searchType: ['base', 'advanced'],
    };
  }

  componentDidMount() {
    const { docSubscribeStore, location } = this.props;
    const { __doSearch, getRightMenu, getConditionInfo, getTreeDatas, setState } = docSubscribeStore;
    const { search } = location;
    let viewtab = GetUrlParam(search, 'viewcondition');
    __doSearch('Subscribe', { viewcondition: viewtab || 3 });
    getRightMenu('Subscribe', { viewcondition: viewtab || 3 });
    getConditionInfo('Subscribe', { viewcondition: viewtab || 3 });
    getTreeDatas('Subscribe', { operation: 'add' });
    setState({ viewcondition: viewtab || 3 });
    docSubscribeStore.broswerDatas = [];
  }

  componentWillReceiveProps(nextProps) {
    const { docSubscribeStore, location } = nextProps;
    const { __doSearch, getRightMenu, getConditionInfo, getTreeDatas, setState, treeSelect } = docSubscribeStore;
    const { search } = location;
    let viewtab = GetUrlParam(search, 'viewcondition');
    __doSearch('Subscribe', { viewcondition: viewtab || 3 });
    getRightMenu('Subscribe', { viewcondition: viewtab || 3 });
    getConditionInfo('Subscribe', { viewcondition: viewtab || 3 });
    getTreeDatas('Subscribe', { operation: 'add' });
    setState({ viewcondition: viewtab || 3 });
    docSubscribeStore.broswerDatas = [];
    treeSelect();
  }

  componentWillUnmount() {
    const { docSubscribeStore } = this.props;
    const { comsWeaTableStore } = docSubscribeStore;
    comsWeaTableStore.setSelectedRowKeys([]);
  }

  onTabSearch = () => {
    const { docSubscribeStore } = this.props;
    let { viewcondition, form, __doSearch, seccategory } = docSubscribeStore;
    __doSearch('Subscribe', { viewcondition, ...form.getFormParams(), seccategory });
  }
  onTabKeyChange = (viewcondition) => {
    const { docSubscribeStore } = this.props;
    let { changeTabKey } = docSubscribeStore;
    changeTabKey(viewcondition);
  }
  getSearchBaseValue = () => {
    const { docSubscribeStore } = this.props;
    const { form } = docSubscribeStore;
    return form.getFormParams()[this.quickSearchPara] || ''
  }
  hideSearchAd = () => {
    const { docSubscribeStore } = this.props;
    const { setState } = docSubscribeStore;
    setState({ showSearchAd: false })
  }
  setShowSearchAd = bool => {
    const { docSubscribeStore } = this.props;
    const { setState } = docSubscribeStore;
    setState({ showSearchAd: bool })
  }
  onSearchChange = (value) => {
    const { docSubscribeStore } = this.props;
    const { form } = docSubscribeStore;
    form.updateFields({ [this.quickSearchPara]: { value } })
  }
  getContent = () => {
    const { docSubscribeStore } = this.props;
    let {
      tabInfo, viewcondition, changeTabKey, showSearchAd, setState
      , comsWeaTableStore, rowSelection, form, __doSearch, seccategory,
    } = docSubscribeStore;
    return (<div>
      <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@fka3zo`}
        datas={toJS(tabInfo)}
        keyParam="viewcondition"
        buttonsAd={this.getTabButtonsAd()}
        selectedKey={viewcondition}
        searchType={this.state.searchType}
        showSearchAd={showSearchAd}
        setShowSearchAd={this.setShowSearchAd}
        hideSearchAd={this.hideSearchAd}
        searchsBaseValue={this.getSearchBaseValue()}
        searchsAd={this.getSearchs()}
        onChange={this.onTabKeyChange}
        onSearch={this.onTabSearch}
        onSearchChange={this.onSearchChange}
      />
      <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@zzdoeq`}
        comsWeaTableStore={comsWeaTableStore}
        hasOrder={true}
        needScroll={true}
        rowSelection={rowSelection}
        onOperatesClick={this.onOperatesClick}
        getColumns={this.getColumns}
      />
    </div>);
  }



  // table重定列
  getColumns = (columns) => {
    const { docSubscribeStore } = this.props;
    const { viewcondition } = docSubscribeStore;
    let newColumns = '';
    if (viewcondition == 1) {
      newColumns = columns.map((item) => {
        let newColumn = item;
        if (newColumn.dataIndex === 'id') {
          newColumn.render = (text, record, index) => (
            <div>
              <WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@ufqynq@${text}`} type={9}
                title={getLabel(22243, '文档')}
                isSingle={false}
                onChange={(ids, names, datas) => {
                  docSubscribeStore.broswerDatas.push({ rowId: record.id, otherSubscribe: `${record.id}-${ids}` });
                }}
              />
            </div>
          );
        }
        return newColumn;
      });
    } else {
      newColumns = columns;
    }
    return newColumns;
  }

  // 右键菜单
  getRightMenu(isTop = false) {
    const { docSubscribeStore } = this.props;
    const {
      comsWeaTableStore, __doSearch, loading, showThumbnails, setState,
      viewcondition, rightMenu, form, onAgree, onReject, onGetBack, onSubmit, selectedRows,
    } = docSubscribeStore;
    // let { selectedRowKeys } = comsWeaTableStore;
    // selectedRowKeys = toJS(selectedRowKeys);
    const loadingNow = loading || comsWeaTableStore.loading;
    const btnArr = [];
    rightMenu.forEach((m) => {
      // let disabled = showThumbnails ? checkedKeys.length === 0 : selectedRowKeys.length === 0;
      let disabled = selectedRows.length === 0;
      let onClick = () => { };
      let content = m.menuName;
      if (m.type === 'BTN_SEARCH') { // 搜索
        disabled = false;
        onClick = () => {
          __doSearch('Subscribe', { viewcondition, ...form.getFormParams() });
        };
      } else if (m.type === 'BTN_COLUMN') { // 显示列定制
        disabled = false;
        onClick = () => {
          comsWeaTableStore.setColSetVisible(true);
          comsWeaTableStore.tableColSet(true);
        };
      } else if (m.type === 'BTN_STORE') { // 收藏
        disabled = true;
        onClick = () => {
        };
      } else if (m.type === 'BTN_HELP') { // 帮助
        disabled = true;
        onClick = () => {
        };
      } else if (m.type === 'BTN_APPROVE') { // 批准
        onClick = () => {
          setState({ recordId: '' });
          onAgree();
        };
      } else if (m.type === 'BTN_REFUSED') { // 退回
        onClick = () => {
          setState({ recordId: '' });
          onReject();
        };
      } else if (m.type === 'BTN_BACK') { // 收回
        onClick = () => {
          setState({ recordId: '' });
          onGetBack();
        };
      } else if (m.type === 'BTN_SUBSCRIPTION') { // 提交
        onClick = () => {
          setState({ recordId: '' });
          onSubmit();
        };
      } else {
        disabled = false;
      }
      disabled = loadingNow || disabled;
      if (isTop) {
        m.isTop === '1' && btnArr.push(
          <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@8gvzs3@${m.type}`} type="primary"
            disabled={disabled}
            onClick={onClick}
          >
            {content}
          </Button>,
        );
      } else {
        m.type !== 'BTN_STORE' && m.type !== 'BTN_HELP' && btnArr.push({
          key: m.type,
          icon: <i className={m.menuIcon} />,
          content,
          disabled,
          onClick,
        });
      }
    });
    return btnArr;
  }


  // 高级搜索按钮
  getTabButtonsAd() {
    const { docSubscribeStore } = this.props;
    const { viewcondition, form, setState, __doSearch } = docSubscribeStore;
    const btns =
      [<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@9mpi45@search`} type="primary"
        onClick={() => {
          __doSearch('Subscribe', { viewcondition, ...form.getFormParams() });
          setState({ showSearchAd: false, checkedKeys: [] });
        }}
      >{getLabel(197, '搜索')}</Button>];
    btns.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@pbjj3j@reset`} type="ghost" onClick={() => form.reset()}>{getLabel(2022, '重置')}</Button>);
    btns.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@7n3q3l@cancel`} type="ghost" onClick={() => setState({ showSearchAd: false })}>{getLabel(31129, '取消')}</Button>);
    return btns;
  }
  onSearch = () => {
    const { docSubscribeStore } = this.props;
    const { viewcondition, form, setState, __doSearch } = docSubscribeStore;
    __doSearch('Subscribe', { viewcondition, ...form.getFormParams() });
    setState({ showSearchAd: false, checkedKeys: [] });
  }
  // 高级搜索条目
  getSearchs() {
    const { docSubscribeStore } = this.props;
    const { conditioninfo, form } = docSubscribeStore;
    const { isFormInit } = form;
    const group = [];
    const formParams = form.getFormParams();
    isFormInit && toJS(conditioninfo).forEach((c) => {
      let items = [];
      c.items.forEach((field) => {
        if (field.isQuickSearch) {
          this.quickSearchPara = field.domkey[0];
        }
        items.push({
          com: (
            <SearchFormItem ecId={`${this && this.props && this.props.ecId || ''}_SearchFormItem@0iy2ep@${field.domkey[0]}`} field={field} form={form} formParams={formParams} onSearch={this.onSearch}/>
          ),
          colSpan: 1,
        });
      });
      group.push(
        <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@o6kvu4@${c.title}`} needTigger={true} title={c.title} showGroup={c.defaultshow} items={items} />,
      );
    });
    return group;
  }

  onOperatesClick=(record, index, operate, flag)=> {
    const { docSubscribeStore } = this.props;
    const { onAgree, onReject, onGetBack, onSubmit, setState } = docSubscribeStore;
    const funName = operate.href.replace(/javascript\:/g, '');
    setState({ recordId: record.id, selectedRowKeys: '' });
    if (record) {
      if (funName === 'add()') {
        setState({
          recordId: record.id,
          selectedRowKeys: '',
          selectedSubject: [record.docsubject],
          selectedRows: [record.id],
          otherSubscribe: '',
        });
        onSubmit();
      } else if (funName === 'onAgree()') {
        setState({ recordId: record.randomFieldId, selectedRowKeys: '' });
        onAgree();
      } else if (funName === 'onReject()') {
        setState({ recordId: record.randomFieldId, selectedRowKeys: '' });
        onReject();
      } else if (funName === 'onGetBack()') {
        setState({ recordId: record.randomFieldId, selectedRowKeys: '', otherSubscribe: '' });
        onGetBack();
      }
    }
  }
  getCollectParams = () => {
    const { title } = this.props.docSubscribeStore;
    return {
      favname: title,
      favouritetype: 2,
      objid: 0,
      importantlevel: 1,
      link: 'wui/index.html#/main/document/subscribe',
    }
  }
  getDropMenuProps = () => {
    const { title } = this.props.docSubscribeStore;
    return {
      collectParams: {
        favname: title,
        favouritetype: 2,
        objid: 0,
        importantlevel: 1,
        link: 'wui/index.html#/main/document/subscribe',
      },
    }
  }
  render() {
    const { docSubscribeStore } = this.props;
    let {
      tabInfo, viewcondition, changeTabKey, title, loading, comsWeaTableStore, form,
      showSearchAd, setState, __doSearch, rowSelection, treeDatas, treeSelect, selectedKeys,
    } = docSubscribeStore;
    treeDatas = toJS(treeDatas);
    const loadingNow = loading || comsWeaTableStore.loading;
    return (
      <div className="wea-doc-subscribe">
        <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@4ienok`}
          datas={this.getRightMenu()}
          collectParams={this.getCollectParams()}
        >
          <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@ksif0y`}
            title={title}
            loading={loading}
            icon={<i className="icon-coms-doc" />}
            iconBgcolor="#df583a"
            buttons={this.getRightMenu(true)}
            buttonSpace={10}
            showDropIcon={true}
            dropMenuDatas={this.getRightMenu()}
            dropMenuProps={this.getDropMenuProps()}
          >
            <div style={{ height: '100%' }}>
              {
                <WeaLeftRightLayout ecId={`${this && this.props && this.props.ecId || ''}_WeaLeftRightLayout@0e89oj`}
                  leftCom={<WeaLeftTree ecId={`${this && this.props && this.props.ecId || ''}_WeaLeftTree@htocwz`} datas={treeDatas} onSelect={treeSelect} selectedKeys={toJS(docSubscribeStore.selectedKeys)} />}
                  children={this.getContent()}
                />
              }
            </div>
          </WeaTop>
          <SubscribeDialog ecId={`${this && this.props && this.props.ecId || ''}_SubscribeDialog@iaiq63`} />
        </WeaRightMenu>
        <Synergy ecId={`${this && this.props && this.props.ecId || ''}_Synergy@7rdsc1`} pathname="/document/subscribe" secid="-1" docid="-1" />
      </div>
    );
  }
}

class SearchFormItem extends React.Component{
  render(){
    const {field,form,formParams,onSearch}=this.props;
      return <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@kj86qh@${field.domkey[0]}`}
      label={`${field.label}`}
      labelCol={{ span: field.labelcol }}
      wrapperCol={{ span: field.fieldcol }}
    >
      <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@x3ijra@${field.domkey[0]}`} fieldConfig={field} form={form} formParams={formParams} onEnterSearch={onSearch} />
    </WeaFormItem>
    }
}

export default Subscribe;
